<template>
  <div class="design-view">
    <je-panel v-bind="lauoutOptions">
      <template #top>
        <div style="overflow: auto; height: 60px; overflow-x: auto; overflow-y: hidden">
          <div class="view-from">
            <span class="from-span">{{ modelRef.tableTypeName }}</span>

            <je-form layout="inline" style="height: 30px; width: 100%">
              <je-row type="flex" justify="space-between" style="width: 100%">
                <je-col :span="6">
                  <je-form-item
                    :label="$t('designView.nameLabel')"
                    :colon="false"
                    name="RESOURCETABLE_TABLENAME"
                    validate-type="tooltip"
                    v-bind="validateInfos.RESOURCETABLE_TABLENAME"
                  >
                    <je-input v-model:value="modelRef.RESOURCETABLE_TABLENAME" allow-clear />
                  </je-form-item>
                </je-col>
                <je-col :span="6">
                  <je-form-item
                    :label="$t('designView.codeLabel')"
                    :colon="false"
                    validate-type="tooltip"
                    name="RESOURCETABLE_TABLECODE"
                    v-bind="validateInfos.RESOURCETABLE_TABLECODE"
                  >
                    <je-input
                      v-model:value="modelRef.RESOURCETABLE_TABLECODE"
                      :disabled="modelRef.RESOURCETABLE_ISCREATE == '1'"
                      allow-clear
                    />
                  </je-form-item>
                </je-col>
                <je-col :span="6">
                  <je-form-item
                    :label="$t('designView.remarkLabel')"
                    :label-col="{
                      style: {
                        width: '50px',
                      },
                    }"
                    name="RESOURCETABLE_REMARK"
                    :colon="false"
                  >
                    <je-input v-model:value="modelRef.RESOURCETABLE_REMARK" allow-clear />
                  </je-form-item>
                </je-col>
                <je-col :span="6">
                  <je-form-item
                    :label="$t('designView.createUserNameText')"
                    name="SY_CREATEUSERNAME"
                    :colon="false"
                  >
                    <je-input
                      v-model:value="modelRef.SY_CREATEUSERNAME"
                      :disabled="disabled"
                      allow-clear
                    />
                  </je-form-item>
                </je-col>
              </je-row>
            </je-form>
          </div>
        </div>
      </template>
      <template #default>
        <je-tabs v-model:activeKey="activeKey" class="designview-tabs">
          <je-tab-pane key="column">
            <template #tab>
              <span>
                <i class="jeicon jeicon-from"></i>
                {{ $t('designView.tabColumnTitle') }}
              </span>
            </template>
            <TableColumn
              :tab-key="tabKey"
              :table-info="modelRef"
              :refresh-column="refreshColumn"
              :column-save="columnSave"
              :column-apply-save="columnApplySave"
              :product-data="productData"
              @refreshHistory="refreshHistory"
              @callColumnSave="callColumnSave"
            />
          </je-tab-pane>
          <je-tab-pane v-if="modelRef.RESOURCETABLE_TYPE != 'VIEW'" key="2">
            <template #tab>
              <span>
                <i class="fal fa-key"></i>
                {{ $t('designView.tabKeyTitle') }}
              </span>
            </template>
            <TableKeys
              :tab-key="tabKey"
              :table-info="modelRef"
              :refresh-key="refreshKey"
              :product-data="productData"
              @refreshHistory="refreshHistory"
            />
          </je-tab-pane>
          <je-tab-pane v-if="modelRef.RESOURCETABLE_TYPE != 'VIEW'" key="3">
            <template #tab>
              <span>
                <i class="fal fa-ballot"></i>
                {{ $t('designView.tabIndexesTitle') }}
              </span>
            </template>
            <TableIndexes
              :tab-key="tabKey"
              :table-info="modelRef"
              :refresh-index="refreshIndex"
              :product-data="productData"
              @refreshHistory="refreshHistory"
            />
          </je-tab-pane>
          <je-tab-pane key="4">
            <template #tab>
              <span>
                <i class="fal fa-history"></i>
                {{ $t('designView.tabHistoryTitle') }}
              </span>
            </template>
            <TableHistory :tab-key="tabKey" :refresh-his="refreshHis" />
          </je-tab-pane>
        </je-tabs>
      </template>
    </je-panel>
  </div>
</template>
<script>
  import { defineComponent, reactive, ref, watch, onBeforeUnmount } from 'vue';
  import { Tabs, Modal, Panel, Form } from '@jecloud/ui';
  import { Row, Col, Input } from 'ant-design-vue';
  import TableColumn from './table-column.vue';
  import TableKeys from './table-keys.vue';
  import TableIndexes from './table-indexes.vue';
  import TableHistory from './history.vue';
  import VueEvent from '../../helper/model/event';
  import { updateData } from '../../api/index';
  import { verifyData } from '../../helper/common';
  import { JE_TABLE_FIELD_SPECIFICATION } from '@/helper/common';
  import { isNotEmpty } from '@jecloud/utils';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'TableDesignView',
    components: {
      JeInput: Input,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeTabs: Tabs,
      JeTabPane: Tabs.TabPane,
      TableColumn,
      TableKeys,
      TableIndexes,
      TableHistory,
      JeRow: Row,
      JeCol: Col,
      JePanel: Panel,
    },
    props: {
      tabKey: {
        type: String,
        default: '',
      },
      tableInfoData: {
        required: true,
        type: Object,
        default: () => {
          return {};
        },
      },
      oldData: {
        required: true,
        type: Object,
        default: () => {
          return {};
        },
      },
      saveType: {
        type: Boolean,
        default: true,
      },
      applyType: {
        type: Boolean,
        default: true,
      },
      refreshColumn: {
        type: Boolean,
        default: true,
      },
      productData: {
        type: Object,
        required: true,
        default: () => {
          return {};
        },
      },
    },
    emits: ['callApplyClick'],
    setup(props, { emit }) {
      //表单数据
      const modelRef = reactive(props.tableInfoData);
      const oldFormData = reactive(props.oldData);
      const rulesRef = reactive({
        RESOURCETABLE_TABLENAME: verifyData.name,
        RESOURCETABLE_TABLECODE: [],
        RESOURCETABLE_REMARK: [verifyData.lengthMax],
      });
      const activeKey = ref('column');
      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
        onValidate: (...args) => {},
      });

      watch(
        () => props.tableInfoData,
        (newVal) => {
          //非导入的表有code校验
          if (newVal.RESOURCETABLE_IMPORT != '1') {
            rulesRef.RESOURCETABLE_TABLECODE = verifyData.code;
          }
        },
        { deep: true },
      );

      //保存操作
      const saveTable = (type) => {
        let flag = true;
        //表单数据没有修改不操作
        const ketArray = [
          'RESOURCETABLE_TABLENAME',
          'RESOURCETABLE_TABLECODE',
          'RESOURCETABLE_REMARK',
        ];
        for (let i in ketArray) {
          const keyItem = ketArray[i];
          if (modelRef[keyItem] != oldFormData[keyItem]) {
            flag = false;
            break;
          }
        }
        if (flag) {
          //调用应用接口
          if (isNotEmpty(type)) {
            if (type == 'dosave') {
              Modal.notice('保存成功！', 'success');
            } else {
              emit('callApplyClick', type);
            }
          } else {
            Modal.notice('无数据操作！', 'info');
          }
          return;
        }
        validate()
          .then(() => {
            updateData({
              tableCode: 'JE_CORE_RESOURCETABLE',
              JE_CORE_RESOURCETABLE_ID: modelRef.JE_CORE_RESOURCETABLE_ID,
              RESOURCETABLE_TABLENAME: modelRef.RESOURCETABLE_TABLENAME.trim(),
              RESOURCETABLE_TABLECODE: modelRef.RESOURCETABLE_TABLECODE.trim(),
              RESOURCETABLE_REMARK: modelRef.RESOURCETABLE_REMARK,
            })
              .then((data) => {
                //关闭弹窗
                if (isNotEmpty(type) && type != 'dosave') {
                  emit('callApplyClick', type);
                } else {
                  Modal.notice(data.message, 'success');
                }
                oldFormData.RESOURCETABLE_TABLENAME = data.data.RESOURCETABLE_TABLENAME;
                oldFormData.RESOURCETABLE_TABLECODE = data.data.RESOURCETABLE_TABLECODE;
                oldFormData.RESOURCETABLE_REMARK = data.data.RESOURCETABLE_REMARK;
                VueEvent.emit('loadData', {
                  title: modelRef.RESOURCETABLE_TABLENAME,
                  key: modelRef.JE_CORE_RESOURCETABLE_ID,
                  type: 'update',
                });
              })
              .catch((e) => {
                if (type != undefined) {
                  emit('callApplyClick', 'notApply');
                }
                Modal.alert(e.message, 'error');
              });
          })
          .catch((err) => {
            if (type != undefined) {
              emit('callApplyClick', 'notApply');
            }
            //console.log('error', err);
          });
      };

      //检测触发保存
      const columnSave = ref(true);
      const columnApplySave = ref(true);
      watch(
        () => props.saveType,
        () => {
          //同时保存表格列修改的数据
          columnSave.value = !columnSave.value;
          //saveTable();
        },
      );

      //检测点击了应用按钮
      watch(
        () => props.applyType,
        () => {
          //先调用表格列保存方法
          columnApplySave.value = !columnApplySave.value;
          //表格列保存后才应用表
        },
      );

      //
      const callColumnSave = (type) => {
        saveTable(type);
      };

      onBeforeUnmount(() => {
        VueEvent.all.delete('saveTableInFo');
      });

      //检测是否刷新历史留痕
      const refreshHis = ref(true);
      const refreshKey = ref(true);
      const refreshIndex = ref(true);
      const refreshHistory = (type) => {
        //如果是修改主键需要刷新表格键/表索引
        if (type == 'addKey') {
          refreshKey.value = !refreshKey.value;
          refreshIndex.value = !refreshIndex.value;
        } else if (type == 'all') {
          refreshKey.value = !refreshKey.value;
          refreshIndex.value = !refreshIndex.value;
          refreshHis.value = !refreshHis.value;
        } else {
          refreshHis.value = !refreshHis.value;
        }
      };

      //应用的时候需要刷新表格列,表格键,表索引
      watch(
        () => props.refreshColumn,
        () => {
          refreshKey.value = !refreshKey.value;
          refreshIndex.value = !refreshIndex.value;
          refreshHis.value = !refreshHis.value;
        },
      );

      watch(
        () => activeKey.value,
        (val) => {
          if (val == '2') {
            refreshKey.value = !refreshKey.value;
          }
          if (val == '3') {
            refreshIndex.value = !refreshIndex.value;
          }
        },
      );

      const getPopupContainer = () => {
        return document.body;
      };

      return {
        saveTable,
        modelRef,
        activeKey,
        validateInfos,
        resetFields,
        disabled: true,
        refreshHistory,
        refreshHis,
        refreshKey,
        callColumnSave,
        refreshIndex,
        columnSave,
        columnApplySave,
        labelCol: {
          span: 6,
        },
        lauoutOptions: { top: { size: 60 } },
        JE_TABLE_FIELD_SPECIFICATION,
        getPopupContainer,
      };
    },
  });
</script>
<style lang="less" scoped>
  .design-view {
    height: 100%;
    .viewtop-button {
      height: 40px;
      line-height: 40px;
      position: relative;
      border-bottom: 1px solid #e6e6e6;
      .button-right {
        position: absolute;
        right: 32px;
        font-size: 14px;
        font-weight: Bold;
        .right-state {
          color: #008103;
        }
        .right-context {
          margin-left: 14px;
          color: #3265f5;
          cursor: pointer;
        }
      }
    }
    .view-from {
      height: 60px;
      display: flex;
      align-items: center;
      min-width: 1000px;
      .from-span {
        font-size: 14px;
        color: #7f7f7f;
        font-weight: Bold;
        margin-left: 16px;
        width: 46px;
      }
      .ant-form {
        margin-left: 15px;
      }
    }
    .designview-tabs {
      height: 100%;
      .ant-tabs-nav {
        height: 40px;
      }
    }
  }
</style>
<style lang="less">
  .design-modal {
    .ant-modal-footer {
      text-align: center;
    }
    p {
      font-size: 16px;
      line-height: 30px;
      color: #333333;
      font-weight: Normal;
    }
  }
  .design-view {
    .designview-tabs {
      .ant-tabs-nav-wrap {
        .ant-tabs-nav-list {
          .ant-tabs-tab {
            padding: 12px 0 !important;
          }
          .ant-tabs-tab.ant-tabs-tab-active {
            background: #f7f9fc !important;
          }
          .ant-tabs-tab + .ant-tabs-tab {
            margin: 0 0 0 32px !important;
          }
          .ant-tabs-tab.ant-tabs-tab-active {
            // background: @component-background !important;
            .ant-tabs-tab-btn {
              color: @primary-color !important;
            }
          }
          .ant-tabs-ink-bar.ant-tabs-ink-bar-animated {
            height: 2px !important;
          }
        }
      }
      .ant-tabs-nav .ant-tabs-nav-wrap {
        padding: 0 0 0 16px;
      }
      .ant-tabs-nav::before {
        border: 0 !important;
      }
    }
  }
  /*  .theme-primary-default
    .designview-tabs
    .ant-tabs-nav-wrap
    .ant-tabs-nav-list
    .ant-tabs-tab.ant-tabs-tab-active {
    background: #f7f9fc !important;
  } */
</style>
